package com.jxust.interceptor;

import com.jxust.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override//目标 方法执行之前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求
        String requestURI = request.getRequestURI();

        //2.判断是否是登录请求，如果路径中包含/login 说明是登录操作放行
        if(requestURI.contains("/login")){
            log.info("登录请求，放行");
            return true;
        }
        //3. 获取请求头中的token
        String token = request.getHeader("token");

        //4.判断token是否存在返回错误信息(401)
        if(token==null||token.isEmpty()){
            log.info("令牌为空,响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //5.如果令牌存在校验令牌，失败401
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            log.info("令牌验证失败，响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //6.通过放行
        log.info("令牌验证成功，放行");
        return true;
    }
}
